<template>
  <div>
    <div class="model-title-css">
      <div class="title">实体质量检测</div>
    </div>

    <div class="background_wrap">
      <div class="operate_wrap flexDiv">
        <div class="flex-left">
          <el-button type="primary" size="small" class="add buildButtonStyle" v-permission="permission.add" round @click="showDialog('build', '实体质量检测新增')">
            <i class="iconfont icon-icon_add"></i>&nbsp;新增
          </el-button>
        </div>
        <div class="flex-right">
          <el-select style="float: none;margin: 0; margin-right:15px;" class="select" size="small" v-model="search.projectId" v-on:change="getList(false)" value-key="id" filterable clearable placeholder="选择项目">
            <el-option v-for="item in projectTree" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
          <el-button class="search" size="small" @click="getList(true)">
            <i class="iconfont icon-sousuo"></i> 搜索
          </el-button>
        </div>
      </div>

      <div class="list_wrap WholeScroll">
        <el-table class="table-four-blue" :border="true" :row-class-name="tableRowStyleName" :cell-class-name="tableCellStyleName" :header-cell-class-name="tableHeaderCellStyleName" :stripe="true" ref="multipleTable" :data="list" tooltip-effect="dark" @cell-click="cellClick" style="width: 100%; font-family: PingFangSC-Regular; font-size: 14px">
          <el-table-column label="序号" type="index" align="center" width="60">
            <template slot-scope="scope">
              <!-- {{scope.$index}} -->
              {{ scope.$index + search.pageNo * search.pageSize + 1 }}
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="projectName" label="项目名称" min-width="160">
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="checkDate" label="检测时间" min-width="120">
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="reportName" label="名称" min-width="340">
            <template slot-scope="scope">
              <div style="text-align: left">{{ scope.row.reportName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="附件" align="center" width="80">
            <template slot-scope="scope">
              <div class="table-iconfont-box row-i-hover-css">
                <i v-if="scope.row.files&&scope.row.files.length>0" class="iconfont icon-a-wenjian1" v-on:click="showFiles(scope.row,'附件')"></i>
              </div>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="createTime" label="填报时间" width="170"></el-table-column>
          <el-table-column show-overflow-tooltip label="操作" width="300" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" class="menu_icon iconfont icon-icon_look action_color1" v-permission="permission.show" @click="showDialog('check','实体质量检测查看',scope.row.id)">&nbsp;查看</el-button>
              <el-button size="mini" class="menu_icon iconfont icon-xiugai-copy action_color1" v-permission="permission.edit" @click="showDialog('edit','实体质量检测编辑',scope.row.id)">&nbsp;修改</el-button>
              <el-button size="mini" class="menu_icon iconfont icon-shanchu action_color2" v-permission="permission.del" @click="showDialog('delete','删除',scope.row.id)">&nbsp;删除</el-button>
            </template>

          </el-table-column>
        </el-table>
        <el-pagination style="float: right; margin-top: 30px" layout="prev, pager, next" :page-size="search.pageSize" :total="search.total" :current-page="search.pageNo + 1" :prev-text="tablePaginationPrev" :next-text="tablePaginationNext" @current-change="paginationChange">
        </el-pagination>
      </div>
    </div>

    <Detail :postDetail="postDetailData" @reloadList="getList(true)"></Detail>
    <!-- <book-detail :postDetail="postAddressDetailData" @reloadList="getList(true)"></book-detail> -->

    <el-dialog width="600px" class="approveDialog" :visible.sync="showFileDialog" :modal-append-to-body="false" :close-on-click-modal="false" append-to-body>
      <span slot="title">
        <i class="iconfont icon-a-wenjian1"></i>
        <span>附件</span>
      </span>
      <el-table :border="true" :header-cell-style="{padding: '0',height:'38px',backgroundColor: '#f2f2f2',textAlign:'center',borderColor: '#d4d4d4'}" :cell-style="{padding: '6px 0',textAlign:'center',borderColor: '#d4d4d4'}" ref="multipleTable" :data="nowFileList" style="width: 100%; font-family: PingFangSC-Regular; font-size: 14px;" @selection-change="handleSelectionChange">

        <el-table-column show-overflow-tooltip label="序号" type="index" width="60">

        </el-table-column>
        <el-table-column show-overflow-tooltip label="文件名" width="320">
          <template slot-scope="scope">
            <div style="text-align: center;" v-html="scope.row.name"></div>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip width="300" label="操作">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="light" content="查看" placement="top">
              <div class="menu_icon" @click="viewFile(scope.row.id)" style="display: inline;cursor:pointer;margin-right: 5px"><i class='iconfont icon-icon_look'></i></div>
            </el-tooltip>
            <el-tooltip class="item" effect="light" content="下载" placement="top">
              <div class="menu_icon" @click="dlFile(scope.row)" style="display: inline;cursor:pointer"><i class='iconfont icon-icon-xiazai'></i></div>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <!--新建和编辑的暂存上报-->
        <el-button size="small" @click="showFileDialog=false"><i class="iconfont icon-icon_cancel"></i> 关 闭
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { tableRowStyleGol, tableCellStyleGol, tableHeaderCellStyleGol, } from '@/utils/publicFun'

import crudProject from '@/api/buss/project'
import crudPhysicalQualityInspection, { listPage } from '@/api/buss/physicalQualityInspection'
import msgUtil from '@/utils/msgUtil'
import crudDict from '@/api/system/dict'
import projectSectionInfo from '@/api/buss/common'
const PREVIEW_URL = process.env.VUE_APP_FILE_PREVIEW
export default {
  name: 'physicalQualityInspection',
  components: {
    Detail: require('./physicalQualityInspection-detail').default,
  },
  data() {
    return {
      permission: {
        add: ['100', 'project:add'],
        show: ['100', 'project:show'],
        edit: ['100', 'project:edit'],
        del: ['100', 'project:del'],
        section: ['100', 'project:section'],
      },
      tableRowStyleName: tableRowStyleGol,
      tableCellStyleName: tableCellStyleGol,
      tableHeaderCellStyleName: tableHeaderCellStyleGol,
      tablePaginationPrev: '上一页',
      tablePaginationNext: '下一页',
      nowFileList: [],
      addCan: true, //是否有新增权限
      contractsAmount: 0,
      projectTree: [],
      showFileDialog: false,
      search: {
        pageNo: 0,
        //pageIndex: 0,
        pageSize: 10,
        //pageSum: 0,
        total: 0,
        status: 'S',
        projectType: '', // 项目类型
        region: '', // 所属区域
        reportName: '', //项目名称
        sortField: 'createTime',
        regionName: '', // 所属区域
        phaseId: '', //所属阶段
        constructionUnit: '', //建设单位
        beginTime: '',
        endTime: '',
      }, // 搜索参数
      typeOptions: [{ label: '项目类型', value: '' }],
      regionOptions: [],
      phaseOptions: [],
      constructionUnitOptions: [
        //建设单位
      ],
      list: [],
      postDetailData: {
        show: false,
        type: 'build',
      },
      postAddressDetailData: {
        show: false,
        type: 'build',
      },
      navigationIndex: 0,
      contractDetail_postDetailData: {
        show: false,
        type: 'check',
      },
    }
  },
  filters: {
    moneyFilter(value) {
      try {
        let before = value.toFixed(2)
        let numFlag = true
        //判断是否正数，是负数就先删掉 - 然后最后加回去
        if (before >= 0) {
          numFlag = true
        } else {
          numFlag = false
        }
        before = before.toString()
        let num = before.split('.')[0]
        if (numFlag !== true) {
          num = num.substr(1, num.length)
        }
        let numSmall = before.split('.')[1]
        let result = [], counter = 0;
        num = (num || 0).toString().split('');
        for (let i = num.length - 1; i >= 0; i--) {
          counter++;
          result.unshift(num[i]);
          if (!(counter % 3) && i != 0) {
            result.unshift(',');
          }
        }
        let after = numSmall === undefined ? result.join('') : result.join('') + '.' + numSmall
        if (numFlag !== true) {
          after = '-' + after
        }
        return after
      } catch (e) {
        return ""
      }
    },
  },
  created() {
    // this.initData()
    this.getList();
    this.getProjSecTreeAll()
  },
  methods: {
    initData() {
      this.typeOptions = []
      this.phaseOptions = []
      this.regionOptions = []
      this.constructionUnitOptions = []
      crudDict.getByCode('project_type').then(res => {
        if (res.code === 200) {
          var data = res.data;
          for (var i in data) {
            this.typeOptions.push({ 'value': data[i].id, 'label': data[i].name });
          }
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("获取项目类型失败")
      })

      crudDict.getByCode('phase_type').then(res => {
        if (res.code === 200) {
          var data = res.data;
          for (var i in data) {
            this.phaseOptions.push({ 'value': data[i].id, 'label': data[i].name });
          }
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("获取阶段类型失败")
      })

      crudDict.getByCode('companyRegion').then(res => {
        if (res.code === 200) {
          var data = res.data;
          for (var i in data) {
            this.regionOptions.push({ 'value': data[i].id, 'label': data[i].name });
          }
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("获取行政等级失败")
      })

      crudProject.getCompanytList().then(res => {
        if (res.status == 1) {
          this.constructionUnitOptions = res.data
        } else {
          msgUtil.error2(res.data.message)
        }
      })
    },

    getProjSecTreeAll() {
      projectSectionInfo.getProjSecTreeAll().then(res => {
        if (res.code === 200) {
          this.$set(this, 'projectTree', res.data)
          if (this.$headerSearch) {
            // console.log(this.search,66665554);
            // this.projectTree.forEach((item) => {
            //   if (item.id === this.search.projectId) {
            //     this.sectionTree = item.children
            //   }
            // })
            // this.getSectionByProjectId()
          }
        } else {
          this.$messageError(res.data.message)
        }
      }).catch(() => {
        this.$messageError('获取项目标段树失败')
      })
    },
    handleSelectionChange(val) {
      this.selectedIds = []
      val.forEach(item => {
        this.selectedIds.push(item.id)
      })
    },
    //切换分页器
    paginationChange(index) {
      this.search.pageNo = index - 1
      this.getList()
    },
    // 获取列表 api
    getList() {
      this.list = []
      let queryData = { ...this.search }
      crudPhysicalQualityInspection.listPage(queryData).then(res => {
        if (res.code == 200) {
          if (res.data.content.length > 0) {
            this.list = res.data.content
            //this.$set(this.list, this.list.length, res.list)
          }
          this.search.total = res.data.totalElements
        } else {
          msgUtil.error2(res.data.msg)
        }
      })
    },
    showFiles(row, title) {
      console.log(row, '=============')
      this.fileTitle = title
      this.nowFileList = row.files

      if (this.nowFileList) {
        this.showFileDialog = true
      }
    },
    //预览
    viewFile(e) {
      this.loading = true
      this.$httpGet('/file-server/file/preview?id=' + e).then(response => {
        this.loading = false;
        //  如果是minio地址路径，则调用kkview
        if (!response.data.startsWith("/")) {
          window.open(PREVIEW_URL + '/onlinePreview?url=' + encodeURIComponent(Base64.encode(response.data)));
        } else {
          //  如果是转换后的previewGetFile，浏览器直接打开
          window.open(response.data);
        }
      }).catch(res => {
        console.log(res)
        this.loading = false;
      })

    },
    //下载文件
    dlFile(e) {
      this.$publicUpload.checkFile(e.id, e.name)
    },
    /*  操作 */
    showDialog(type, typeName, detailId) {
      switch (type) {
        case 'build':
          this.postDetailData = {
            show: true,
            type: type,
            typeName: typeName,
            detailId: '',
          }
          break
        case 'edit':
          this.postDetailData = {
            show: true,
            type: type,
            typeName: typeName,
            detailId: detailId,
          }
          break
        case 'check':
          this.postDetailData = {
            show: true,
            type: type,
            typeName: typeName,
            detailId: detailId,
          }
          break
        case 'addressBook':
          this.postAddressDetailData = {
            show: true,
            type: type,
            typeName: typeName,
            detailId: detailId.id,//
            companyId: detailId.constructionUnitId,
          }
          break
        case 'delete':
          if (detailId === '') {
            msgUtil.error2('请先选择要删除的记录！')
            return
          }
          msgUtil.confirm('确认删除该条数据?').then(res => {
            let idlist = []
            idlist.push(detailId)
            let param = {
              ids: idlist
            }
            crudPhysicalQualityInspection.del(param).then(res => {
              let { code, msg } = res
              if (code == 200) {
                msgUtil.success2('删除成功!')
                this.getList()
              } else {
                msgUtil.error2(msg)
              }
            })
          })
          break
        case 'section':
          this.$router.push({ path: '/projectManagement/sectionManage', query: { id: detailId } })
          break
      }
    },
    // 点击单元格
    cellClick(row, column, cell, event) {
      // console.log(row, column, cell, event)
      console.log(column)
      //如果点击的是“来源” --跳出合同的弹窗
      // if (column.property === 'source') {
      //   this.handleClickDeal({
      //     type: 'contract_show',
      //     detailId: row.id,
      //     actions: row.actions,
      //   })
      // }
      if (column.property === 'reportName') {
        this.showDialog('check', '实体质量检测查看', row.id)
      }
    },
  },
}
</script>

<style scoped lang="scss">
.top {
  width: 100%;
  height: 40px;
  margin-top: 10px;
  .title {
    float: left;
    font-family: PingFangSC-Regular;
    font-size: 18px;
    font-weight: 600;
  }
}
.operate_wrap {
  width: 100%;
  .select {
    // width: 200px;
    width: 150px;
  }
  .input {
    // width: 200px;
    width: 150px;
    margin: 0 15px;
  }
  .search {
    width: 88px;
    color: #fff;
  }
}
.list_wrap {
  margin-top: 20px;
}
.navigation {
  width: 100%;
  height: 40px;
  box-sizing: border-box;
  border-bottom: 1px solid #313e50;
  margin-top: 5px;
  .el-button {
    height: 40px;
    background: #374256;
    border: 1px solid #374256;
    font-family: PingFangSC-Regular;
    border-radius: 5px 5px 0 0;
    min-width: 95px;
    font-size: 14px;
    color: #8190a7;
    &:hover {
      background-color: #f2f2f2;
    }
    &[selected] {
    }
  }
  .el-button + .el-button {
    margin-left: 0;
  }
}
.icon-a-wenjian1 {
  font-size: 26px;
}
</style>
